<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="采购退货单明细"
        @returnBack="returnBack"
        :btnList="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button
            v-if="
              $permission('purchReturn:print') && infoList.data.status !== 1
            "
            @click="print"
            >打印</el-button
          > -->
          <el-button
            v-if="
              ($permission('purchReturn:submit') &&
                infoList.data.status === 1) ||
              infoList.data.status === 5
            "
            @click="submit"
            >提交</el-button
          >
          <el-button
            v-if="
              $permission('purchReturn:update') &&
              (infoList.data.status === 1 || infoList.data.status === 5)
            "
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('purchReturn:export') && infoList.data.status === 2
            "
            @click="outStock"
            >出库</el-button
          >
          <el-button
            v-if="
              $permission('purchReturn:invalid') && infoList.data.status === 2
            "
            @click="invalidUp"
            >作废</el-button
          >
          <el-button
            v-if="
              $permission('purchReturn:retract') && infoList.data.status === 3
            "
            @click="breakUp"
            >撤回</el-button
          >
          <el-button
            v-if="
              $permission('purchReturn:breakUpExport') &&
              infoList.data.status === 'pend_receive'
            "
            @click="breakUpStock"
            >撤回出库</el-button
          >
          <el-button v-if="canCancelDownTransfer" @click="cancelDownTransfer"
            >取消拣货</el-button
          >
          <el-button
            v-if="$permission('purchReturn:exportExcel')"
            :plain="true"
            @click="exportExcel"
            >导出excel</el-button
          >
        </template>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation :info="infoList"> </BasicInformation>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 表格 -->
            <PageTable
              :refresh="tableInfo.refresh"
              :init-curpage="tableInfo.initCurpage"
              v-model:data="tableInfo.data"
              :pager="false"
              :summary="true"
              :check-box="false"
              :tab-index="true"
              :summaryFieldList="tableInfo.summaryFieldList"
              :field-list="tableInfo.fieldList"
              :handle="tableInfo.handle"
              :isDynamic="true"
            >
              <template v-slot:col-storeBatchNumber="scope">
                <StoreBatchNumberTag :row="scope.row" />
              </template>
            </PageTable>
          </div>
        </div>
      </NewFullScreen>
    </div>

    <IndividualDetails
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      v-model:query="individualInfo.query"
      :info="individualInfo.info"
    />
    <purchReturnModify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :purchReturnId="modifyInfo.purchReturnId"
    />
  </div>
</template>

<script setup name="purchReturnDetail">
import {
  purchReturnDetailsCustomizeListAll,
  detailPurchReturn,
  getPurchReturnOrderDetail,
  purchReturnSubmit,
  purchReturnExport,
  purchReturnRetract,
  purchReturnInvalid,
  purchReturnBreakUpExport,
  getPurchReturnPrint,
  excelPurchReturn,
  purchCancelDownShelf,
} from '@/api/purch.js'
import { orderAffairAll } from '@/api/affair'
import StoreBatchNumberTag from '@/views/stock/components/StoreBatchNumberTag'
import IndividualDetails from './IndividualDetails'
import purchReturnModify from './modify'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  purchReturnId: {
    type: [String, Number],
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.purchReturnId,
      },
    },
    queryParams: {},
  },
})
const fullInfo = ref({
  btnList: [{ type: 'slot', value: 'button' }],
})
const infoList = ref({
  data: {},
  fieldList: [
    { label: '退货单号', value: 'orderNo' },
    { label: '供应商', value: 'supplierName' },
    { label: '状态', value: 'statusValue' },
    { label: '申请人', value: 'createUserName' },
    { label: '部门', value: 'deptName' },
    { label: '退货仓库', value: 'depotName' },
    { label: '采购退货类型', value: 'returnTypeValue' },
    { label: '退货联系人', value: 'contact' },
    { label: '联系人电话', value: 'phone' },
    { label: '申请时间', value: 'createTime' },
    { label: '退货时间', value: 'returnTime' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '引用合同编号',
      value: 'quoteContractNos',
      type: 'text',
      show: false,
    },
    {
      label: '采购依据',
      value: 'purchAccordingValue',
      type: 'text',
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: individualDetails,
        show: true,
        ifRender: ifIndividualDetails,
      },
    ],
  },
})
const affairTableInfo = ref({
  query: {
    orderType: 1,
    orderId: props.purchReturnId,
    sort: 'operate_time desc',
  },
})
const paramsIndividual = ref({})
const showIndividualDetails = ref(false)
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const modifyInfo = ref({
  visible: false,
  title: '',
  purchReturnId: '',
})
const canPrint = computed(() => {
  return (
    proxy.$permission('purchReturn:print') && infoList.value.data.status !== 1
  )
})
const canCancelDownTransfer = computed(() => {
  return (
    proxy.$permission('purchReturn:cancelDown') &&
    infoList.value.data.status === 9
  )
})
watch(
  () => modifyInfo.value.visible,
  (val) => {
    if (!val) {
      getMain()
      getList()
    }
  }
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
function ifIndividualDetails(row) {
  // 待出库 待收货 完成 已拒收 已作废  24678
  return (
    infoList.value.data.isCargoSpaceManage === 0 ||
    (infoList.value.data.isCargoSpaceManage === 1 &&
      [2, 4, 6, 7, 8].includes(row.status))
  )
}
//导出excel
function exportExcel() {
  excelPurchReturn(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function returnBack() {
  proxy.$emit('returnBack', false)
}

//提交
function submit() {
  const ids = [infoList.value.data.id]
  purchReturnSubmit(ids).then((resp) => {
    if (resp.success) {
      getCustomize()
    }
  })
}
function outStock() {
  const ids = [infoList.value.data.id]
  purchReturnExport(ids).then((resp) => {
    if (resp.success) {
      getCustomize()
    }
  })
}
function invalidUp() {
  const ids = [infoList.value.data.id]
  purchReturnInvalid(ids).then((resp) => {
    if (resp.success) {
      getCustomize()
    }
  })
}
//取消上架
function cancelDownTransfer() {
  proxy
    .$confirm('确认取消拣货吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let params = { id: infoList.value.data.id }
      purchCancelDownShelf(params).then((resp) => {
        if (resp && resp.success) {
          getCustomize()
        }
      })
    })
    .catch(() => {})
}
function breakUp() {
  const ids = [infoList.value.data.id]
  purchReturnRetract(ids).then((resp) => {
    if (resp.success) {
      getCustomize()
    }
  })
}
function breakUpStock() {
  const ids = [infoList.value.data.id]
  purchReturnBreakUpExport(ids).then((resp) => {
    if (resp.success) {
      getCustomize()
    }
  })
}
function individualDetails(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  console.log(row, 'row')
  individualInfo.value.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.purchReturnId,
    },
  }
  individualInfo.value.info = row
  individualInfo.value.visible = true
}
function update() {
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改采购退货单'
  modifyInfo.value.purchReturnId = props.purchReturnId
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'purchReturnDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.purchReturnId,
            deptId: infoList.value.data.deptId,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.purchReturnId,
      tempCode: 'purchReturnDetail',
      orderType: 1,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.purchReturnId,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'purchPurchReturnDetail-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
    orderIds: [props.purchReturnId],
  }
  getPurchReturnPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('purchReturn:price')
      )
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      data.forEach((item) => {
        if (item.operateType === 'out_bound') {
          infoList.value['data'] = {
            ...infoList.value.data,
            returnTime: item.operateTime,
          }
        }
      })
      break
  }
}
function getMain() {
  detailPurchReturn(props.purchReturnId).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
    }
  })
}
function getList() {
  purchReturnDetailsCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
      if (!(infoList.value.data.purchAccording == '2')) {
        tableInfo.value.fieldList.forEach((item) => {
          if (item.value === 'quoteContractNo') {
            item['hidden'] = true
          }
        })
      } else {
        infoList.value.fieldList.forEach((item) => {
          if (item.value === 'quoteContractNos') {
            item['show'] = true
          }
        })
      }
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'purchPurchReturnDetail-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchReturn:price'),
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchReturn:price'),
    show: false,
    hidden: true,
  },
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('purchReturn:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  storeBatchNumber: {
    label: '入库批次号',
    value: 'storeBatchNumber',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
</script>
